package com.gitee.flow.cdi;

import com.gitee.jmash.core.orm.cdi.DataSourceConfig;
import javax.sql.DataSource;
import org.flowable.cdi.CdiStandaloneProcessEngineConfiguration;
import org.flowable.common.engine.impl.history.HistoryLevel;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngineConfiguration;

/**
 * Jmash CDI ProcessEngine.
 *
 * @author cgd
 */
public class JmashProcessEngineLookup implements org.flowable.cdi.spi.ProcessEngineLookup {

  ProcessEngine defaultProcessEngine;

  @Override
  public int getPrecedence() {
    return 20;
  }

  @Override
  public synchronized ProcessEngine getProcessEngine() {
    if (null != defaultProcessEngine) {
      return defaultProcessEngine;
    }
    DataSource writeDataSource = DataSourceConfig.getWriteDataSource();
    ProcessEngineConfiguration cfg = new CdiStandaloneProcessEngineConfiguration()
        .setDataSource(writeDataSource).setAsyncExecutorActivate(false)
        .setActivityFontName("WenQuanYi Zen Hei")
        .setLabelFontName("WenQuanYi Zen Hei")
        .setAnnotationFontName("WenQuanYi Zen Hei")
        .setHistoryLevel(HistoryLevel.FULL)
        .setAsyncExecutorActivate(false)
        .setTransactionsExternallyManaged(true)
        .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
    defaultProcessEngine = cfg.buildProcessEngine();
    return defaultProcessEngine;
  }

  @Override
  public void ungetProcessEngine() {
    defaultProcessEngine.close();
  }

}
